#pragma once
#include <iostream>
#include <sys/socket.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <arpa/inet.h>

class Sock{
	public:
	static int SOCKET(){
		int sock = socket(AF_INET,SOCK_STREAM,0);
		if(sock<0){
			std::cerr<<"socket error"<<std::endl;
		}
		int opt = 1;
		setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
		return sock;
	}

	static void BIND(int sock,uint16_t port){
		struct sockaddr_in local;
		memset(&local,0,sizeof(local));
		local.sin_family = AF_INET;
		local.sin_port = htons(port);
		local.sin_addr.s_addr = INADDR_ANY;

		if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0){
			std::cerr<<"bind error"<<std::endl;		
		}
	}

	static void LISTEN(int sock){
		if(listen(sock,5) < 0){
			std::cerr<<"listen error"<<std::endl;
		}
	}

	static int ACCEPT(int sock){
		struct sockaddr_in peer;
		socklen_t len = sizeof(peer);
		memset(&peer,0,sizeof(peer));
		int fd = accept(sock,(struct sockaddr*)&peer,&len);
		if(fd < 0){
			std::cerr<<"accept error"<<std::endl;
			return -1;
		}
		return fd;
	}

	static void CONNECT(int sock,std::string ip,uint16_t port){
		struct sockaddr_in server;
		memset(&server,0,sizeof(server));
		server.sin_family = AF_INET;
		server.sin_port = htons(port);
		server.sin_addr.s_addr = inet_addr(ip.c_str());
		if(connect(sock,(struct sockaddr*)&server,sizeof(server))==0){
			std::cout<<"connect success"<<std::endl;
		}
		else{
			std::cerr<<"connect error"<<std::endl;
		}
	}
};

